package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室服务端
 */
public class Server {
    private ServerSocket serverSocket;
    private List<PrintWriter> allOut = new ArrayList<>();

    /**
     * 服务端构造器
     */
    public Server() {
        try {
            System.out.println("正在启动服务端..");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void start() {
        int index = 1;
        try {
            while (true) {
                System.out.println("等待客户端连接..");
                Socket socket = serverSocket.accept();
                System.out.println("客户端" + (index++) + "已连接");
                ClientHanlder hanlder = new ClientHanlder(socket);
                Thread t = new Thread(hanlder);
                t.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    /**
     * 读写信息
     */
    private class ClientHanlder implements Runnable {
        private Socket socket;
        private String host;

        public ClientHanlder(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {
            PrintWriter pw = null;
            try  {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(),
                                StandardCharsets.UTF_8));
                pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream())),true);
                //同步add方法
                synchronized (allOut){
                    //将输出流存入共享集合
                    allOut.add(pw);
                }
                System.out.println(host+"上线了，当前在线人数："+allOut.size());
                String s;
                while ((s = br.readLine()) != null) {
                    System.out.println(host + "说:" + s);
                    //迭代集合时不能增删all out元素
                    synchronized (allOut){
                        for (PrintWriter o : allOut) {//将消息回复给所有客户端
                            o.println(host + "说:" + s);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {    //处理客户端断开后的操作

                synchronized (allOut){
                    allOut.remove(pw);//将当前客户端输出流从集合中删除
                }

                System.out.println(host+"下线了，当前在线人数："+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
